package im.starchat.chat.activity.old;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;

import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.ButterKnife;
import butterknife.InjectView;
import im.starchat.chat.R;
import im.starchat.chat.XLApplication;
import im.starchat.chat.activity.BaseActivity;
import im.starchat.chat.activity.WebViewActivity;
import im.starchat.chat.activity.account.LoginActivity;
import im.starchat.chat.activity.profile.AboutUsActivity;
import im.starchat.chat.activity.profile.ApplyActivity;
import im.starchat.chat.activity.profile.DebugModeActivity;
import im.starchat.chat.activity.profile.EditUserAddressActivity;
import im.starchat.chat.activity.profile.EditUserDescribeActivity;
import im.starchat.chat.activity.profile.EditUserNameActivity;
import im.starchat.chat.rest.RestClient;
import im.starchat.chat.rest.model.UserBean;
import im.starchat.chat.rest.model.api.UpTokenResponse;
import im.starchat.chat.rest.model.api.UserSettingResponse;
import im.starchat.chat.utils.ActivityManager;
import im.starchat.chat.utils.BitmapHelp;
import im.starchat.chat.utils.FileUtils;
import im.starchat.chat.utils.GsonUtil;
import im.starchat.chat.utils.ImageUtil;
import im.starchat.chat.utils.PreferencesStorageUtil;
import im.starchat.chat.utils.UserUtils;
import im.starchat.chat.view.CircularImageButton;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;


//setting
public class SettingActivity extends BaseActivity implements View.OnClickListener{
    public static final String TAG = "SettingActivity";
    private static final int ERROR_INTNET = -1;
    private static final int UPDATE_USER_SEX = 1;
    private static final int UPDATE_USER_SIGNATURE = UPDATE_USER_SEX + 1;
    private static String IMAGE_FILE_LOCATION = "file:///sdcard/head.jpg";


    // 设置头像
    private static final int IMAGE_REQUEST_CODE = 0; // 请求码 本地图片
    private static final int CAMERA_REQUEST_CODE = 1; // 拍照
    private static final int RESULT_REQUEST_CODE = 2; // 裁剪
    private static final String SAVE_AVATORNAME = "head.jpeg";// 保存的图片名

    // 设置头像
    private final static int SELECT_PIC_KITKAT = 3;
    private final static int SELECT_PIC = 4;
    private final static int REQ_CODE_PHOTO_CROP = 5;
    private final static int REQ_CODE_CAMERA = 6;


    private Uri mCameraImageUri, mImageUri;
    private Uri imageUri;
    private Context ctx;
    private CircularImageButton btnImage;
//    private String mHeadPath;
    private Dialog dialog;
//    private UserInfo mSelfUserInfo;
//    private String userPhone ;
    private TextView mUserNameTextView;
    private TextView mUserSexTextView;
    private TextView mUserAddressTextView;
    private TextView mUserSignatureTextView;
    File mFile;

    @InjectView(R.id.notification_attention)
    CheckBox mAttentionNotifyCheckBox;
    @InjectView(R.id.notification_sys)
    CheckBox mSysCheckBox;
    @InjectView(R.id.user_id)
    TextView mUserId;
    @InjectView(R.id.apply_layout)
    RelativeLayout mApplyLayout;
    @InjectView(R.id.privacy_layout)
    RelativeLayout mPrivacyLayout;
    @InjectView(R.id.aboutus_layout)
    RelativeLayout mAboutUsLayout;

    @InjectView(R.id.debug_layout)
    RelativeLayout mDebugLayout;

    private ImageLoader imageLoader = ImageLoader.getInstance();

    private String mImageKey = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.personal_center_activity);
        ButterKnife.inject(this);
        ctx = this;
        initData();
        initView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }


    private void initData() {
        File galleryFile = new File(XLApplication.catchDir + "/" + "icon"
                + new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date()));
        mImageUri = Uri.fromFile(galleryFile);

        File cameraFile = new File(XLApplication.cameraDir, new SimpleDateFormat("yyyyMMdd-HHmmss")
                .format(new Date()) + ".jpg");
        mCameraImageUri = Uri.fromFile(cameraFile);
    }

    private void initView() {


        mImageKey = PreferencesStorageUtil.getUserId(SettingActivity.this) + System.currentTimeMillis() + ".jpg";
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
                this).threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .discCacheFileNameGenerator(new Md5FileNameGenerator())
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                .writeDebugLogs().build();
        ImageLoader.getInstance().init(config);

        Button mExitButton = (Button)findViewById(R.id.btn_exit);
        mUserNameTextView = (TextView) findViewById(R.id.user_name);
        mUserSexTextView = (TextView) findViewById(R.id.user_sex);
        mUserAddressTextView = (TextView) findViewById(R.id.user_address);
        mUserSignatureTextView = (TextView) findViewById(R.id.user_signature);
        ImageView mReturnImageButton = (ImageView) findViewById(R.id.btn_person_return);
        btnImage = (CircularImageButton) findViewById(R.id.userimage);
//        mSelfUserInfo = ((XLApplication) getApplication()).getMyselfUserInfo();
//        mHeadPath = ImageConstant.ROOT_DIR + PreferencesStorageUtil.getUserId(this) + "_head.jpg";
//        userPhone = mSelfUserInfo.getUserPhone();
        IMAGE_FILE_LOCATION = "file:///sdcard/"+ PreferencesStorageUtil.getUserId(this) + "_head.jpg";
        imageUri = Uri.parse(IMAGE_FILE_LOCATION);

//        initUserHeadImage();
        if(!TextUtils.isEmpty(UserUtils.getUserInstance().getAvatar())){
            imageLoader.displayImage(UserUtils.getUserInstance().getAvatar(), btnImage);
        }
//        mUserNameTextView.setText(mSelfUserInfo.getUserName());
//        mUserAddressTextView.setText(mSelfUserInfo.getUserAddr().length() > 0 ? mSelfUserInfo.getUserAddr() : "未知");
//        mUserSignatureTextView.setText(mSelfUserInfo.getUserSignature());

        findViewById(R.id.user_image_relativelayout).setOnClickListener(this);
        findViewById(R.id.user_name_relativelayout).setOnClickListener(this);
        findViewById(R.id.user_sex_relativelayout).setOnClickListener(this);
        findViewById(R.id.user_address_relativelayout).setOnClickListener(this);
        findViewById(R.id.user_signature_relativelayout).setOnClickListener(this);

        mReturnImageButton.setOnClickListener(this);
        mExitButton.setOnClickListener(this);
        mUserSignatureTextView.setOnClickListener(this);
        btnImage.setOnClickListener(this);
        mPrivacyLayout.setOnClickListener(this);
        mAboutUsLayout.setOnClickListener(this);
        if(PreferencesStorageUtil.isDebugMode(SettingActivity.this)){
            mDebugLayout.setVisibility(View.VISIBLE);
            mDebugLayout.setOnClickListener(this);
        }

        initUserUI();

        getUserSetting();

        mApplyLayout.setOnClickListener(this);



    }

    private void putSetting(boolean follow_notice, boolean system_sg_notice){
        showProgressDialog();
        XLApplication.getInstance().getRestClient().putSetting(follow_notice, system_sg_notice, new Callback<UserSettingResponse>() {
            @Override
            public void success(UserSettingResponse userSettingResponse, Response response) {
                dismissProgressDialog();
                toast("修改成功", Toast.LENGTH_SHORT);
            }

            @Override
            public void failure(RetrofitError error) {
                dismissProgressDialog();
            }
        });
    }

    private void getUserSetting(){
        XLApplication.getInstance().getRestClient().getSetting(new Callback<UserSettingResponse>() {
            @Override
            public void success(UserSettingResponse userSettingResponse, Response response) {
                if(userSettingResponse != null){
                    mAttentionNotifyCheckBox.setChecked(userSettingResponse.isFollow_notice());
                    mSysCheckBox.setChecked(userSettingResponse.isSystem_msg_notice());
                    mAttentionNotifyCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                        @Override
                        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                            putSetting(isChecked, mSysCheckBox.isChecked());
                        }
                    });
                    mSysCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                        @Override
                        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                            putSetting(mAttentionNotifyCheckBox.isChecked(), isChecked);
                        }
                    });
                }
            }

            @Override
            public void failure(RetrofitError error) {

            }
        });
    }

    private void initUserUI(){
        if(UserUtils.getUserInstance() != null){
            mUserId.setText(UserUtils.getUserInstance().getId() + "");
            mUserNameTextView.setText(UserUtils.getUserInstance().getNickname());
            if(!TextUtils.isEmpty(UserUtils.getUserInstance().getAddress()) ){
                mUserAddressTextView.setText(UserUtils.getUserInstance().getAddress());
            }else{
                mUserAddressTextView.setText("未设置");
            }
            if(!TextUtils.isEmpty(UserUtils.getUserInstance().getDescription()) ){
                mUserSignatureTextView.setText(UserUtils.getUserInstance().getDescription());
            }else{
                mUserSignatureTextView.setText("填写个人签名");
            }
            if(!TextUtils.isEmpty(UserUtils.getUserInstance().getGender_text())){
                mUserSexTextView.setText(UserUtils.getUserInstance().getGender_text());
            }else{
                mUserSexTextView.setText("未填写");
            }
            if(PreferencesStorageUtil.isDebugMode(SettingActivity.this)){
                mDebugLayout.setVisibility(View.VISIBLE);
                mDebugLayout.setOnClickListener(this);
            }
        }
    }

    /**
     * 将头像保存在SDcard
     */
    public void saveMyBitmap(Bitmap bitmap)
    {
        if(bitmap != null && FileUtils.createOrExistsFolder(ImageUtil.getImageCachePath())){
            File f = new File(ImageUtil.getImageCachePath(),
                    SAVE_AVATORNAME);
            try
            {
                f.createNewFile();
                FileOutputStream fOut = new FileOutputStream(f);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);

                fOut.flush();
                fOut.close();
                mFile = f;
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }

    }


    // 选择图片来源
    private void showOptionsDialog()
    {
        String[] items = new String[] { "拍照", "选择本地图片" };

        DialogInterface.OnClickListener click = new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                switch (which)
                {
                    case 0://拍照
                        Intent camera = new Intent("android.media.action.IMAGE_CAPTURE");
                        camera.putExtra("output", mCameraImageUri);
                        startActivityForResult(camera, REQ_CODE_CAMERA);
                        break;
                    case 1://选择本地图片

                        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                            intent.addCategory(Intent.CATEGORY_OPENABLE);
                            intent.setType("image/jpeg");
                            startActivityForResult(intent, SELECT_PIC_KITKAT);
                        } else {
                            Intent intent = new Intent();
                            intent.setType("image/*");
                            intent.setAction(Intent.ACTION_GET_CONTENT);
                            startActivityForResult(intent, SELECT_PIC);
                        }
                        break;
                }
            }
        };

        new AlertDialog.Builder(this).setItems(items,
                click).show();
    }


    @Override
    protected void onResume() {
        super.onResume();
        initUserUI();
    }

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case ERROR_INTNET:
                    break;

                default:
                    break;
            }

            return false;
        }
    });



    private void saveHeadTOServer() {


        XLApplication.getInstance().getRestClient().upToken("headerCover/" + mImageKey, new Callback<UpTokenResponse>() {
            @Override
            public void success(UpTokenResponse nullResponse, Response response) {

                UploadManager uploadManager = new UploadManager();
                uploadManager.put(ImageUtil.getImageCachePath() + "/" + SAVE_AVATORNAME, "headerCover/" + mImageKey, nullResponse.getUptoken(),
                        new UpCompletionHandler() {
                            @Override
                            public void complete(String key, ResponseInfo info, JSONObject response) {

                                Log.d(TAG, "key--->" + key);
                                Log.d(TAG, "ResponseInfo--->" + info.statusCode);
                                Log.d(TAG, "response--->" + response.toString());

                                imageLoader.displayImage(RestClient.BASE_IMG_URL + key, btnImage);
                                XLApplication.getInstance().getRestClient().putUserInfoAvatar(PreferencesStorageUtil.getUserId(SettingActivity.this), RestClient.BASE_IMG_URL + key, new Callback<UserBean>() {
                                    @Override
                                    public void success(UserBean userBean, Response response) {
                                        PreferencesStorageUtil.setUserBean(SettingActivity.this, GsonUtil.toJson(userBean));
                                        UserUtils.setUserInstance(userBean);
                                        toast("修改成功!", Toast.LENGTH_SHORT);
                                        dismissProgressDialog();
//                    PreferencesStorageUtil.setStar(EditUserNameActivity.this, true);
                                        finish();
                                    }

                                    @Override
                                    public void failure(RetrofitError error) {
                                        dismissProgressDialog();
                                        toast("修改失败", Toast.LENGTH_SHORT);
                                    }
                                });

                            }
                        }, null);
            }

            @Override
            public void failure(RetrofitError error) {

            }
        });

    }

//    private void takePhoto() {
//        ImageConstant.PhotoClassflag = ImageConstant.HEAD;
//        File outputImage = new File(Environment.getExternalStorageDirectory(), "tempImage.jpg");
//        File destDir = new File(ImageConstant.ROOT_DIR);
//        if (!destDir.exists()) {
//            if(!destDir.mkdirs()) {
//                Log.d(TAG, "DEBUG mkdirs fail");
//            }
//        }
//        try {
//            if (outputImage.exists() && outputImage.delete()) {
//                Log.d(TAG, "DEBUG deletedirs success");
//            }
//            outputImage.createNewFile();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//        ImageConstant.imageuri = Uri.fromFile(outputImage);
//        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//        intent.putExtra(MediaStore.EXTRA_OUTPUT, ImageConstant.imageuri);
//        startActivityForResult(intent, ImageConstant.TAKE_PHOTO);
//    }
//
//    private void getUserHeadImage() {
//        File outputImage = new File(Environment.getExternalStorageDirectory(), "output.jpg");
//        File destDir = new File(ImageConstant.ROOT_DIR);
//        if (!destDir.exists()) {
//            destDir.mkdirs();
//        }
//        try {
//            if (outputImage.exists()) {
//                outputImage.delete();
//            }
//            outputImage.createNewFile();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//        ImageConstant.imageuri = Uri.fromFile(outputImage);
//        Intent intent = new Intent("android.intent.action.PICK");
//        intent.setType("image/*");
//        intent.putExtra("crop", true);
//        intent.putExtra("scale", true);
//        intent.putExtra(MediaStore.EXTRA_OUTPUT, ImageConstant.imageuri);
//        startActivityForResult(intent, ImageConstant.SELECT_PHOTO);
//    }
//
//    public void startPhotoZoom(Uri uri) {
//        Intent intent = new Intent("com.android.camera.action.CROP");
//        intent.setDataAndType(uri, "image/*");
//        intent.putExtra("crop", "true");
//        intent.putExtra("aspectX", 1);
//        intent.putExtra("aspectY", 1);
//        intent.putExtra("outputX", 800);
//        intent.putExtra("outputY", 800);
////        intent.putExtra("return-data", true);
//        intent.putExtra("return-data", false);
////        intent.putExtra("output", imageUri);
//        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
//        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
//        startActivityForResult(intent, ImageConstant.CROP_PHOTO);
//    }

    /**
     * 裁剪图片方法实现
     */
    public void startPhotoZoom(Uri uri)
    {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 600);
        intent.putExtra("outputY", 600);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, RESULT_REQUEST_CODE);
    }


    boolean hasPic = false;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d(TAG, "return:" + requestCode + " " + resultCode);


        switch (requestCode)
        {
            case SELECT_PIC_KITKAT:
                // 从相册返回
                Uri localUri = data.getData();
                if (localUri == null) {
                    return;
                }
                String path = BitmapHelp.getPath(this, localUri);
                System.out.println("SELECT_PIC_KITKAT--path->" + path);
                if(!TextUtils.isEmpty(path)){
                    Uri uri = Uri.fromFile(new File(path));
                    readLocalImage(uri);
                }

                break;
            case SELECT_PIC:
                // 从相册返回
                Uri mUri = data.getData();
                System.out.println("SELECT_PIC_KITKAT--mUri->" + mUri.getAuthority() + "   " +  mUri.getPath());
                if (mUri == null) {
                    return;
                }
                readLocalImage(mUri);
                break;
            case REQ_CODE_CAMERA:
                // 从相机返回,从设置相机图片的输出路径中提取数据
                readLocalImage(mCameraImageUri);
                break;
            case REQ_CODE_PHOTO_CROP:
                Bitmap bitmap = BitmapFactory.decodeFile(mImageUri.getPath());
                saveMyBitmap(bitmap);
                hasPic = true;
                saveHeadTOServer();
                btnImage.setImageBitmap(bitmap);
                break;

//            case IMAGE_REQUEST_CODE:
//                startPhotoZoom(data.getData());
//                break;
//            case CAMERA_REQUEST_CODE:
//                startPhotoZoom(Uri.fromFile(new File(ImageUtil.getImageCachePath(), SAVE_AVATORNAME)));
//                break;
//            case RESULT_REQUEST_CODE:
//                if (data != null)
//                {
//                    Bundle extras = data.getExtras();
//                    if (extras != null)
//                    {
//                        Bitmap photo = extras.getParcelable("data");
//                        saveMyBitmap(photo); // 保存裁剪后的图片到SD
//                        hasPic = true;
//                        mImageButtonLiveCover.setImageBitmap(photo);
//                    }
//                }
//                break;
        }
    }

    private void readLocalImage(Uri uri) {
        if (uri != null) {
            startPhotoCrop(uri, REQ_CODE_PHOTO_CROP); // 图片裁剪
        }
    }

    private void startPhotoCrop(Uri uri, int reqCode) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // crop为true是设置在开启的intent中设置显示的view可以剪裁
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX,outputY 是剪裁图片的宽高
        intent.putExtra("outputX", 600);
        intent.putExtra("outputY", 600);
        intent.putExtra("output", mImageUri);
        intent.putExtra("return-data", false);
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, reqCode);
    }


    /**
     * 保存裁剪之后的图片数据
     */
    private void getImageToView(Intent data)
    {
        Bundle extras = data.getExtras();
        if (extras != null)
        {
            Bitmap photo = extras.getParcelable("data");
            saveMyBitmap(photo); // 保存裁剪后的图片到SD
            saveHeadTOServer();
            btnImage.setVisibility(View.VISIBLE);
        }
    }



    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_person_return:
                finish();
                break;
            case R.id.btn_exit:
                onExit();
                break;
//            case R.id.btn_about:
//            case R.id.btn_about_label:
//                onAbout();
//                break;
            case R.id.userimage:
                onUserImageClick();
                break;
            case R.id.user_image_relativelayout:
                onUserImageClick();
                break;
            case R.id.user_name_relativelayout:
                Intent editUserNameIntent = new Intent();
                editUserNameIntent.setClass(SettingActivity.this, EditUserNameActivity.class);
                startActivity(editUserNameIntent);
                break;
            case R.id.user_sex_relativelayout:
                onUserSex();
                break;
            case R.id.user_address_relativelayout:
                Intent editAddressIntent = new Intent();
                editAddressIntent.setClass(SettingActivity.this, EditUserAddressActivity.class);
                startActivity(editAddressIntent);
                break;
            case R.id.user_signature_relativelayout:
                Intent editDescribeIntent = new Intent();
                editDescribeIntent.setClass(SettingActivity.this, EditUserDescribeActivity.class);
                startActivity(editDescribeIntent);
                break;
            case R.id.apply_layout:
                Intent applyIntent = new Intent();
                applyIntent.setClass(SettingActivity.this, ApplyActivity.class);
                startActivity(applyIntent);
                break;
            case R.id.privacy_layout:
                Intent privayIntent = new Intent();
                privayIntent.setClass(SettingActivity.this, WebViewActivity.class);
                privayIntent.putExtra(WebViewActivity.WEBVIEW_TITLE_FLAG, "隐私条款");
                privayIntent.putExtra(WebViewActivity.WEBVIEW_URL_FLAG, "http://starschats.dalongkeji.com/user_agree.html");
                startActivity(privayIntent);
                break;
            case R.id.aboutus_layout:
                Intent aboutusIntent = new Intent();
                aboutusIntent.setClass(SettingActivity.this,AboutUsActivity.class);
                startActivity(aboutusIntent);
                break;
            case R.id.debug_layout:
                Intent debugIntent = new Intent();
                debugIntent.setClass(SettingActivity.this, DebugModeActivity.class);
                startActivity(debugIntent);
                break;
            default:
                break;
        }
    }


    private void onUserImageClick() {
        if(FileUtils.isSDCardMounted()){
            showOptionsDialog();
        }else{
            toast("没有安装SD卡!", Toast.LENGTH_SHORT);
        }
    }



    private String userSex;
    private void onUserSex() {
        dialog = new Dialog(this, R.style.dialog);
        dialog.setContentView(R.layout.sex_dialog);
        RadioButton femaleBtn = (RadioButton) dialog.findViewById(R.id.female);
        femaleBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                userSex = "female";
            }
        });

        RadioButton maleBtn = (RadioButton) dialog.findViewById(R.id.male);
        maleBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                userSex = "male";
            }
        });

        userSex = UserUtils.getUserInstance().getGender();
        if(userSex.equals("female")) {
            femaleBtn.setChecked(true);
        } else  if( userSex.equals("male")) {
            maleBtn.setChecked(true);
        }

        Button btnOk = (Button) dialog.findViewById(R.id.btn_ok);
        btnOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                saveUserSex(userSex);
            }
        });

        dialog .setCanceledOnTouchOutside(false);
        dialog.show();
    }

    private void onExit() {
        dialog = new Dialog(this, R.style.dialog);
        dialog.setContentView(R.layout.exit_dialog);
        Button exitOk = (Button) dialog.findViewById(R.id.btn_exit_ok);
        Button exitCancel = (Button) dialog.findViewById(R.id.btn_exit_cancel);

        exitOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PreferencesStorageUtil.logout(SettingActivity.this);
//                mSelfUserInfo.logout(getApplicationContext());
                Intent loginIntent = new Intent();
                loginIntent.setClass(SettingActivity.this, LoginActivity.class);
                loginIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                ActivityManager.getInstance().close();
                startActivity(loginIntent);
                finish();
            }
        });
        exitCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        dialog .setCanceledOnTouchOutside(false);
        dialog.show();
    }



    private void saveUserSex(String userSex) {

        showProgressDialog();
        XLApplication.getInstance().getRestClient().putUserInfoGender(PreferencesStorageUtil.getUserId(SettingActivity.this), userSex,new Callback<UserBean>() {
            @Override
            public void success(UserBean userBean, Response response) {
                PreferencesStorageUtil.setUserBean(SettingActivity.this, GsonUtil.toJson(userBean));
                UserUtils.setUserInstance(userBean);
                toast("修改成功!", Toast.LENGTH_SHORT);
                dismissProgressDialog();
//                    PreferencesStorageUtil.setStar(EditUserNameActivity.this, true);
            }

            @Override
            public void failure(RetrofitError error) {
                dismissProgressDialog();
                toast("修改失败", Toast.LENGTH_SHORT);
            }
        });
    }



    public String getVersion() {
        try {
            PackageManager manager = getPackageManager();
            PackageInfo info = manager.getPackageInfo(getPackageName(), 0);
            String version = info.versionName;
            int versionCode = info.versionCode;
            return version + "." + versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 把Uri 转换成bitmap
     * @param uri
     * @return
     */
    private Bitmap decodeUriAsBitmap(Uri uri) {
        Bitmap bitmap = null;
        try {
            // 先通过getContentResolver方法获得一个ContentResolver实例，
            // 调用openInputStream(Uri)方法获得uri关联的数据流stream
            // 把上一步获得的数据流解析成为bitmap
            bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
        return bitmap;
    }
}

